/**
 * Created by Tuffy on 2016/11/30.
 */
'use strict';

var request = require('request');

var baseConfig = require('../resource/base-config');
var sessionUtils = require('../utils/session-utils');
var urlWhiteList = require('../resource/url-whitelist');

var adminHost = 'adminHost';
var tmsdriverHost = 'tmsdriverHost';

module.exports = distributionService;

// 声明
function distributionService() {}

// get请求
distributionService.get = function (req, res, callback) {
    checkTokenLegality(req, function (result) {
        if (result.success) {
            var url = req.query.url;
            var splitUrl = url.split('?');
            var query = '?';
            if (splitUrl.length > 1) {
                query += splitUrl[1];
            }
            get(splitUrl[0], query, req, callback);
        } else {
            callback(result);
        }
    });
};

// post 请求
distributionService.post = function (req, res, callback) {
    checkTokenLegality(req, function (result) {
        if (result.success) {
            post(req.query.url, req, callback);
        } else {
            callback(result);
        }
    });
};

distributionService.getUrl = function (host,url,action) {
    return baseConfig[host] + url + action;
};

/**
 * 登录
 * @param req
 * @param res
 * @param callback
 */
distributionService.login = function(req, res, callback) {
    post('/login', req, callback);
};

distributionService.exportExcel = function(req, res, callback) {
    request.get({url: baseConfig[tmsdriverHost] + "/" + req.query.url + "?name=" + req.query.name + "&phone=" + req.query.phone, json: true}, function(err, res, body) {
        if (!err && res.statusCode === 200) {
            if (callback) {
                callback(body);
            }
        } else {
            callback({success: false, message: '请求异常'});
        }
    });
};

/**
 * get request
 * @param queryString
 * @param req
 * @param callback
 */
function get(url, queryString, req, callback) {
    var host = req.query.host || adminHost;
    console.log(baseConfig[host] + url);
    request.get({
        qs: parseUrlParams(queryString),
        json: true,
        url: baseConfig[host] + url,
        headers: {
            'Authorization': parseUseSession(req)
        }
    }, function(err, res, body) {
        if (!err && res.statusCode === 200) {
            if (callback) {
                callback(body);
            }
        } else {
            callback({success: false, message: '请求异常'});
        }
    });

    // 解析url
    function parseUrlParams(url) {
        url = url.replace(/\?/gi, '');
        var urlArray = url.split('&');
        var params = {};
        for (var i = 0;i < urlArray.length; i++) {
            var item = urlArray[i];
            var itemArray = item.split('=');
            params[itemArray[0]] = itemArray[1];
        }
        return params;
    }
}

/**
 * post request
 * @param url
 * @param req
 * @param callback
 */
function post(url, req, callback) {
    var host = req.query.host;
    request.post({
        json: true,
        url: (baseConfig[host] || baseConfig.adminHost) + url,
        headers: {
            'Authorization': parseUseSession(req)
        },
        form: req.body
    }, function(err, res, body) {
        if (!err && res.statusCode === 200) {
            var result = body;
            // 登录写入token
            if (result && result.success && result.Authorization) {
                sessionUtils.setToken(req, result.Authorization);
                delete result.Authorization;
            }
            callback(result);
        } else {
            callback({success: false, message: '请求异常'});
        }
    });
}

/**
 * 校验系统票据可用性
 * @param req
 * @param callback
 */
function checkTokenLegality(req, callback) {
    // 白名单
    var url = req.query.url;
    console.log('验证URL',url);
    for (var i = 0; i < urlWhiteList.length; i++) {
        if (url.indexOf(urlWhiteList[i]) >= 0) {
            if (callback) callback({success: true, message: '当前系统白名单'});
            return;
        }
    }
    // 菜单校验
    request.get({
        json: true,
        url: baseConfig.adminHost + '/node/menu',
        headers: {
            'Authorization': sessionUtils.getToken(req),
            'menu': req.header('menu')
        }
    }, function(err, res, body) {
        if (!err && res.statusCode === 200) {
            var result = body;
            if (result.success) {
                // 下一步操作
                if (!req.query.host || req.query.host === adminHost) {
                    if (callback) callback({success: true, message: '当前系统票据'});
                    return;
                }
                request.post({
                    json: true,
                    url: baseConfig.adminHost + '/node/legality',
                    headers: {
                        'Authorization': sessionUtils.getToken(req)
                    },
                    form: {
                        host: baseConfig[req.query.host],
                        phone: baseConfig.ticketUser.phone,
                        password: baseConfig.ticketUser.password
                    }
                }, function(err, res, body) {
                    if (!err && res.statusCode === 200) {
                        var result = body;
                        if (result.success) {
                            var baseToken = sessionUtils.getBaseToken(req);
                            if (baseToken != result.data) {
                                sessionUtils.setBaseToken(req, result.data);
                            }
                        }
                    }
                    if (callback) callback(result);
                });
            }
        } else {
            if (callback) callback({success: false, message: '请求异常'});
        }
    });
}

/**
 * 解析token使用
 * @param host 主机地址
 * @returns {string} token
 */
function parseUseSession(req) {
    var sessionToken = null;
    var host = req.query.host;
    if (host && host !== adminHost) {
        sessionToken = sessionUtils.getBaseToken(req);
    } else {
        sessionToken = sessionUtils.getToken(req);
    }
    return sessionToken;
}